package com.dogkr.server.web.guest;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import com.dogkr.common.FileDirEnum;
import com.dogkr.common.ServerAction;
import com.sean.common.action.BaseAction;
import com.sean.common.exception.ActionException;
import com.sean.common.utils.StringUtils;

/**
 * 所下载文件相关的的几个属性:文件格式 contentType, 
 * 获取文件名的方法inputName,
 * 文件内容（显示的）属性contentDisposition, 
 * 限定下载文件 缓冲区的值bufferSize
 * */
@Namespace(value = "/tools")
@Results({ 
	@Result(name = "success", type = "stream", params = { 
		"ContentDisposition","attachment;fileName=\"${fileName}\"",
		"contentType", "image/JPEG",
		"charset","ISO8859-1",
		"inputName", "inputStream",
		"bufferSize", "4096" }),
		
	@Result(name="DOWNLOAD",type="redirect",location="${fileName}")
})
@Action(value = "download")
public class DownloadAction extends ServerAction {
	private static final long serialVersionUID = 8784555891643520648L;
	
	private FileDirEnum dir;
	
	private String fileName;
	
	private File inputPath;// 指定要被下载的文件路径

	public InputStream getInputStream() throws Exception {
		return new FileInputStream(inputPath);
	}
	
	@Override
	public String execute() {
		try {
			if(StringUtils.isBlank(fileName)) {
				return ERROR;
			}
			inputPath = new File(dir.getDirPath(), fileName);
			if(!inputPath.exists()) {
				throw new ActionException("文件获取失败.");
			}
			fileName = inputPath.getName();
		} catch (ActionException e) {
			log.warn("下载获取文件失败.DirPath:" + dir + ", fileName:" + fileName + ", id:" + id, e);
			return ERROR;
		}
		return SUCCESS;
	}

	public FileDirEnum getDir() {
		return dir;
	}

	public void setDir(FileDirEnum dir) {
		this.dir = dir;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
}
